//
// Created by Administrator on 2020-2-13.
//

#include "DataStructre.h"
#include "Operate.h"
#include <stdio.h>
#include <stdlib.h>

void grow(bookList * context);

// 数据持续化
void save(bookList * context){
    FILE *fp;
    fp = fopen("./data.bin", "wb+");
    if (fp == NULL)
        puts("Fail to open file!");
    fwrite(&context->len, sizeof(int), 1, fp);
    fwrite(&context->cap, sizeof(int), 1, fp);
    for (int i = 0; i < context->len; ++i) {
        fwrite(&context->list[i], sizeof(bookInfo), 1, fp);
    }
    fclose(fp);
    puts("保存成功");
}

// 数据读取
void load(bookList * context){
    FILE *fp;
    fp = fopen("./data.bin", "r");
    if (fp == NULL){
        puts("Fail to open file!");
    }
    fread(&context->len, sizeof(int), 1, fp);
    fread(&context->cap, sizeof(int), 1, fp);
    int count = context->len;
    context->len = 0;
    free(context->list);
    context->list = (bookInfo *)malloc(context->cap * sizeof(bookInfo));
    for (int i = 0; i < count; ++i) {
        grow(context);
        fread(&context->list[i], sizeof(bookInfo), 1, fp);
        context->len++;
    }
    fclose(fp);
}
